package com.csdj.server.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @ClassName: CaptchaController
 * @Author: ZouLi
 * @Description: 验证码Controller
 * @Date: 2022/12/15 10:02
 **/
@RestController
@Api(tags = "验证码控制器")
public class CaptchaController {
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @GetMapping(value = "/captcha",produces = "image/jpeg")
    @ApiOperation(value = "获取验证码")
    public void captcha(HttpServletRequest request, HttpServletResponse response){
        // 定义response输出类型为image/jpeg格式
        response.setDateHeader("Expires",0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control","no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control","post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma","no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");

        // 生成验证码
        String code = defaultKaptcha.createText();
        System.out.println("验证码内容："+code);
        // 将验证码放入session
        request.getSession().setAttribute("captcha",code);
        // 根据文本内容创建图像验证码
        BufferedImage image = defaultKaptcha.createImage(code);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            // 输出流输出图片
            ImageIO.write(image,"jpg",out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
